import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { BusinessCircleService } from '../business-circle.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { DatePipe } from '@angular/common';
import { ProblemTypeStatusPipe } from '../status.pipe';
import { PermissionService } from '../../../service/permission.service';
import { DomSanitizer } from '@angular/platform-browser';
import { defalutImg } from '../comm';
import { NzModalService } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-posts-details',
  templateUrl: './posts-details.component.html',
  styleUrls: ['./posts-details.component.scss'],
  providers: [DatePipe, ProblemTypeStatusPipe]
})
export class PostsDetailsComponent implements OnInit {

  // 默认图片
  fallback: any = defalutImg;
  routerParams: any = {};
  issueStatusSelected: any = ''; // 问题状态选中

  preLoading: boolean = true; // 上一页loading
  nextLoading: boolean = false; // 下一页loading
  commentLoading: boolean = false; // 评论loading
  replyLoading: boolean = false; // 回复loading
  moreLoading: boolean = false; // moreloading

  // 详情data
  detailedData: any = {};
  commentContent: string = ''; // 评论textarea
  
  commentTabs: any = [
    { type: 0, text: '正序' },
    { type: 1, text: '倒序' },
  ];
  sortActive: any = null;
  // 评论list
  commentList: any = [];
  // 回复评论params
  commentParams: any = {
    content: '', // 回复内容
    userId: '',
    page: 1,
    pageSize: 10,
    total: 0
  };
  // 关联账号下拉
  relationOptions: any = [];
  // 关联账号选中
  relationSelected: any = '';
  isCommentSpinning: boolean = false;
  
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private datePipe: DatePipe,
    private problemTypeStatusPipe: ProblemTypeStatusPipe,
    private services: BusinessCircleService,
    public permission: PermissionService,
    private modal: NzModalService,
    private sanitizer: DomSanitizer
  ) {
    this.activatedRoute.params.subscribe((res: any) => {
      this.routerParams = res || {};
    });
  }

  ngOnInit(): void {
    this.getCircleList();
    this.loadDetailsData();
    this.loadCommentList();
  }

  // 查询关联账号
  async getCircleList() {
    try {
      const res: any = await this.services.queryCircleManageTableData();
      if (res.code == 0) {
        this.relationOptions = res.data || [];
      }
    } catch (error) {
      this.relationOptions = [];
    }
  }

  // loadDetails
  async loadDetailsData(id?: any, num?: number) {
    try {
      if (num == 0) {
        this.preLoading = true;
      } else {
        this.nextLoading = true;
      }
      const res: any = await this.services.queryPostsDetailsData({id: id || this.routerParams.id});
      this.preLoading = false;
      this.nextLoading = false;
      
      if (res.code == 0) {
        res.data.content = this.sanitizer.bypassSecurityTrustHtml(res.data.content);
        this.detailedData = res.data || {};
        this.issueStatusSelected = res.data.issueStatus;
      } else {
        this.message.error(res.message || '详情获取失败');
      }
    } catch (error: any) {
      this.preLoading = false;
      this.nextLoading = false;
      this.message.error(error);
    }
  }

  // 查询评论列表
  async loadCommentList(isMore?: any, id?: any) {
    try {
      let params: any = {
        postsId: id || this.routerParams.id,
        page: this.commentParams.page,
        pageSize: this.commentParams.pageSize,
        sort: this.sortActive
      }

      this.isCommentSpinning = true;
      const res: any = await this.services.queryCommentListData(params);
      
      this.isCommentSpinning = false;
      if (res.data.records && res.data.records.length > 0) {
        res.data.records.map((item: any) => item.isComment = false);
      }
      
      if (res.code == 0) {
        if (isMore) {
          this.commentList = this.commentList.concat(res.data.records || []);
        } else {
          this.commentList = res.data.records || [];
        }
        
        this.commentParams.total = res.data.total || 0;
      }
    } catch (error) {
      this.isCommentSpinning = false;
      this.commentList = [];
      this.commentParams.total = 0;
    }
  }

  // 上下页
  turnPages(id: any, num: number) {
    this.loadDetailsData(String(id));
    this.commentParams.page = 1;
    this.loadCommentList(null,String(id));
  }

  // 状态修改
  statusChange(ev: any) {
    let tempStr = this.problemTypeStatusPipe.transform(ev);
    // return
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: `<b style="color: red;">是否要把问题标记为 ${tempStr} </b>`,
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        try {
          const res: any = await this.services.updatePostsItemData({id: this.routerParams.id, issueStatus: this.issueStatusSelected});
          if (res.code == 0) {
            this.message.success('状态修改成功');
            this.loadDetailsData(this.detailedData.id);
          } else {
            this.message.error(res.message || '状态修改失败');
            this.issueStatusSelected = this.detailedData.issueStatus;
          }
        } catch (error: any) {
          this.message.error(error);
          this.issueStatusSelected = this.detailedData.issueStatus;
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => {
        this.issueStatusSelected = this.detailedData.issueStatus;
      }
    });
  }

  // 下架帖子
  offShelfPost() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '<b style="color: red;">是否要下架该条帖子，下架后该帖子及相关评论将不再向用户展示</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.offShelfInterface();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
  // 下架 interface
  async offShelfInterface() {
    try {
      const res: any = await this.services.updatePostsItemData({id: this.routerParams.id, status: 2});
      if (res.code == 0) {
        this.message.success('帖子下架成功');
        this.loadDetailsData(this.detailedData.id);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 评论
  async commentSub() {
    if (!this.relationSelected) {
      this.message.warning('请选择关联账号');
      return
    }

    let params: any = { 
      content: this.commentContent, // 评论
      postsId: this.routerParams.id, // 帖子id
      postsUserId: this.detailedData.userId, // 帖子人发送ID
      toUserId: this.detailedData.userId, // 被评论的人ID
      userId: this.relationSelected // 用户ID
    }
    
    // return
    try {
      this.commentLoading = true;
      const res: any = await this.services.sendCommentData(params);
      this.commentLoading = false;
      if (res.code == 0) {
        this.message.success('评论成功');
        this.commentContent = '';
        this.relationSelected = '';

        this.commentParams.page = 1;
        // this.commentList = [];
        this.loadCommentList();
      } else {
        this.message.error(res.message || '评论失败');
      }
    } catch (error: any) {
      this.commentLoading = false;
      this.message.error(error);
    }
  }

  // 排序
  sortChange(num: number) {
    this.sortActive = num;
    this.commentParams.page = 1;
    // this.commentList = [];
    this.loadCommentList();
  }

  // 删除评论
  async delComment(item: any) {
    try {
      const res: any = await this.services.deleteCommentData({id: item.id});
      if (res.code == 0) {
        this.message.success('评论删除成功');
        this.commentParams.page = 1;
        this.loadCommentList();
      } else {
        this.message.error(res.message || '评论删除失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 评论列表回复open | close
  commentChange(item: any, index: number) {
    this.commentList.forEach((ele: any) => {
      if (item.id == ele.id) {
        ele.isComment = !ele.isComment;
      } else {
        ele.isComment = false;
      }
    });
  }
  // 回复
  async replySub(item: any) {
    if (!this.commentParams.userId) {
      this.message.warning('请选择关联账号');
      return
    }
    
    let params: any = {
      content: this.commentParams.content, // 回复内容
      postsId: item.postsId, // 帖子id
      postsUserId: item.postsUserId, // 帖子人发送id
      commentId: item.id, // 关联评论id
      userId: this.commentParams.userId, // 用户id(关联账号)
      toUserId: item.userId // 被评论的人
    }
    
    try {
      this.replyLoading = true;
      const res: any = await this.services.sendCommentData(params);
      this.replyLoading = false;
      if (res.code == 0) {
        this.message.success('评论回复成功');
        this.commentParams.content = '';
        this.commentParams.userId = '';

        this.commentParams.page = 1;
        this.loadCommentList();
      } else {
        this.message.error(res.message || '评论回复失败');
      }
    } catch (error: any) {
      this.replyLoading = false;
      this.message.error(error);
    }
  }

  // 加载更多
  loadMore() {
    this.commentParams.page += 1;
    this.loadCommentList('more');
  }
}
